<template>
  <div>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="dialogAddRole = true">
            添加角色
          </el-button>
        </el-col>
      </el-row>
    </el-card>
    <!-- 表格 -->
    <el-table :data="roleList" style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="scope">
          <div>
            <el-row
              :class="['bdbottom', index === 0 ? 'bdtop' : '']"
              v-for="(item, index) in scope.row.children"
              :key="index"
            >
              <!-- 第一列 -->
              <el-col :span="5">
                <el-tag closable @close="removeTag(scope.row, item.id)">{{
                  item.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 子菜单 -->
              <el-col :span="19">
                <el-row
                  :class="[key === 0 ? '' : 'bdtop']"
                  v-for="(val, key) in item.children"
                  :key="key"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      type="success"
                      @close="removeTag(scope.row, val.id)"
                      >{{ val.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      closable
                      type="warning"
                      v-for="(value, keys) in val.children"
                      :key="keys"
                      @close="removeTag(scope.row, value.id)"
                      >{{ value.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="#" prop="id" width="80"> </el-table-column>
      <el-table-column label="角色名称" prop="roleName" width="180">
      </el-table-column>
      <el-table-column label="角色描述" prop="roleDesc" width="240">
      </el-table-column>
      <el-table-column label="操作" prop="desc">
        <template slot-scope="scope" width="240">
          <el-button
            type="primary"
            icon="el-icon-edit"
            @click="editRole(scope.row.id)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            @click="deleRole(scope.row)"
            >删除</el-button
          >
          <el-button
            type="warning"
            icon="el-icon-s-check"
            @click="showSetRootDialog(scope.row)"
            >分配权限</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 权限分配对话框 -->
    <el-dialog
      title="权限分配"
      :visible.sync="dialogSetRoot"
      @close="exitTree()"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rootList"
        :props="rootProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogSetRoot = false">取 消</el-button>
        <el-button type="primary" @click="setRoleRoot">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="dialogAddRole">
      <el-form :model="addRoleData">
        <el-form-item label="角色名">
          <el-input
            v-model="addRoleData.roleName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色介绍">
          <el-input
            v-model="addRoleData.roleDesc"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAddRole = false">取 消</el-button>
        <el-button type="primary" @click="addRoleRequest">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="编辑角色" :visible.sync="dialogEditRole">
      <el-form :model="addRoleData">
        <el-form-item label="角色名">
          <el-input
            v-model="addRoleData.roleName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色介绍">
          <el-input
            v-model="addRoleData.roleDesc"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEditRole = false">取 消</el-button>
        <el-button type="primary" @click="editRoleRequest">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleList: [], //角色列表数据
      rootList: [], //权限列表数据
      defKeys: [], //默认选择的数据
      rootProps: {
        //这是树形控件绑定json子数据的对象
        label: "authName",
        children: "children",
      },
      addRoleData: {
        //和编辑公用
        roleName: "",
        roleDesc: "",
      },
      dialogSetRoot: false, //权限分配对话框状态
      dialogAddRole: false, //添加
      dialogEditRole: false,
      roleId: "", //分配权限用的角色id,和编辑公用
    };
  },
  methods: {
    getRoleList() {
      //获取权限列表
      this.$req.get(`roles`).then((res) => {
        let {
          data: { data, meta },
        } = res;
        this.roleList = data;
        console.log(data);
      });
    },
    removeTag(role, rootid) {
      //删除权限标签
      console.log(role);
      //弹框删除
      this.$confirm("此操作将删除改权限, 是否继续?", "提示", {
        //这是一个弹出提示框
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then((res) => {
          //按确定后执行的
          if (res === "confirm") {
            this.$req
              .delete(`roles/${role.id}/rights/${rootid}`) //删除请求
              .then((res) => {
                let {
                  data: { data, meta },
                } = res;
                if (meta.status === 200) {
                  this.$message.success(meta.msg);
                  // this.getRoleList()
                  role.children = data;
                }
              });
          }
        })
        .catch((err) => {
          //按取消后执行的
          if (err !== "confirm") {
            this.$message.error("取消了删除");
          }
        });
    },
    showSetRootDialog(role) {
      // 打开分配权限窗口
      this.roleId = role.id;
      this.$req.get(`/rights/tree`).then((res) => {
        let {
          data: { data, meta },
        } = res;
        if (meta.status !== 200) {
          return this.$message.error(meta.msg);
        }
        this.rootList = data;
        this.getDefKeys(role, this.defKeys);
        this.dialogSetRoot = true;
      });
    },
    getDefKeys(node, arr) {
      //通过递归的形式获取角色下所有三级权限的id并保存到数组中
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => {
        this.getDefKeys(item, arr);
      });
    },
    exitTree() {
      // 监听权限对话框关闭事件
      // console.log('关了');
      this.defKeys = [];
    },
    //点击为角色分配权限
    setRoleRoot() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const rootId = keys.join(",");
      this.$req
        .post(`roles/${this.roleId}/rights`, { rids: rootId })
        .then((res) => {
          //  console.log(res);
          let {
            data: { meta },
          } = res;
          if (meta.status === 200) {
            this.$message.success(meta.msg);
            this.getRoleList();
            this.dialogSetRoot = false;
          }
        });
    },
    addRoleRequest() {
      let { roleName, roleDesc } = this.addRoleData;
      this.$req.post(`roles`, { roleName, roleDesc }).then((res) => {
        // console.log(res);
        let {
          data: { meta },
        } = res;
        if (meta.status === 201) {
          this.$message.success(meta.msg);
          this.dialogAddRole = false;
          this.getRoleList();
        }
      });
    },
    editRole(id) {
      //打开编辑角色界面
      this.dialogEditRole = true;
      this.roleId = id;
    },
    editRoleRequest() {
      //发送编辑角色请求
      let { roleName, roleDesc } = this.addRoleData;
      this.$req
        .put(`roles/${this.roleId}`, { roleName, roleDesc })
        .then((res) => {
          let {
            data: { data, meta },
          } = res;
          if (meta.status !== 200) {
            return this.$message.error(meta.msg);
          } else {
            this.$message.success(meta.msg);
            this.getRoleList();
            this.dialogEditRole = false;
          }
        });
    },
      deleRole(scope){
        this.$req.delete(`roles/${scope.id}`)
        .then(res=>{
          let {data:{meta}} = res
          if (meta.status !== 200) {
           return this.$message.error(meta.msg)
          }else {
            this.$message.success(meta.msg)
            this.getRoleList()
          }
        })
      }
  },
  mounted() {
    this.getRoleList();
  },
};
</script>

<style>
.el-table__header {
  line-height: 0;
}
.el-card {
  line-height: 0;
  display: flex;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.el-table {
  line-height: 0;
}
</style>